package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserReportVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    public static final String GRANT_TYPE = "authorization_code";
    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) {
        //发送请求获取openid
        String s = getString(userLoginDTO);
        //{"session_key":"KigQTIY3lIinzo7qGZbD1w==","openid":"oYiMb5HO5nnDwNQ2bMyYNytct7io"}
        String openid = (String) JSONObject.parseObject(s).get("openid");
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //判断当前用户是否为新用户
        User dbUser = userMapper.findByOpenid(openid);
        if(dbUser != null){
            return dbUser;
        }
        //如果是新用户，自动完成注册
        User user = User.builder()
                .openid(openid)
                .createTime(LocalDateTime.now())
                .build();
        userMapper.addUser(user);
        return user;
    }


    /**
     * 发送请求获取openid
     */
    private String getString(UserLoginDTO userLoginDTO) {
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type",GRANT_TYPE);
        return HttpClientUtil.doGet(WX_LOGIN_URL, paramMap);
    }
}
